package com.atgion.manager.controller;

import com.atgion.manager.service.FileUploadService;
import com.atgion.spzx.model.vo.base.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/admin/system")
public class FileUploadController {

    @Autowired
    FileUploadService fileUploadService;

//    将图片保存到Minio中
    @PostMapping("/fileUpload")
    public Result<String> fileUpload(MultipartFile file){
        String url = fileUploadService.upload(file);
        return Result.success(url);
    }
@PostMapping("/icon")
public Result<String> icon(@RequestParam("file") MultipartFile file,
                           @RequestParam(value = "imageName", required = false) String imageName,
                           @RequestParam(value = "jImageName", required = false) String jImageName) {
    try {
        String originalFilename = file.getOriginalFilename();
        String savedFilePath; // 新增：记录最终保存路径
        if(jImageName != null){
            Path dirPath = Paths.get(imageName);
            if (!Files.exists(dirPath)) {
                Files.createDirectories(dirPath);
            }

            // 构造文件路径并保存
            Path filePath = dirPath.resolve(jImageName+".svg");
            file.transferTo(filePath.toFile());
            savedFilePath = filePath.toString(); // 记录完整路径

        } else {
            Path targetPath = Path.of(imageName).normalize().resolve(originalFilename);
            file.transferTo(targetPath);
            savedFilePath = targetPath.toString(); // 记录完整路径
        }

        return Result.success(savedFilePath); // 返回文件完整路径供后续删除使用
    } catch (Exception e) {
        e.printStackTrace();
        return Result.failed("文件上传失败: " + e.getMessage());
    }
}

    @DeleteMapping("/deleteIcon")
    public Result<String> deleteFile(
            @RequestParam(value = "imageName") String imageName, // 必须传目录路径
            @RequestParam(value = "jImageName") String jImageName) { // 必须传文件名
        try {
            // 1. 构建完整文件路径
            Path dirPath = Paths.get(imageName);
            Path filePath = dirPath.resolve(jImageName + ".svg");

            // 2. 直接删除文件（无需检查目录）
            boolean isDeleted = Files.deleteIfExists(filePath);

            if (isDeleted) {
                return Result.success("文件删除成功");
            } else {
                return Result.failed("文件不存在");
            }
        } catch (IOException e) {
            return Result.failed("删除失败: " + e.getMessage());
        }
    }




}
